home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / c / pthd-0.000 / pthd-0 / pthd-0.7 / src_mutex / mutex.c.1 < prev    next >
Encoding:
Text File  |  1995-08-16  |  1.7 KB  |  87 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include "error_msg.h"
  5.  
  6. #define DEFAULT_ITERATIONS ((int) 1)
  7.  
  8. static void    init_mu( pthread_mutex_t *mu );
  9. static void    destroy_mu( pthread_mutex_t *mu );
  10. static void    lock( void );
  11.  
  12. static pthread_mutex_t mutex;
  13. static pthread_t       th;
  14.  
  15. int 
  16. main( int argc, char *argv[] )
  17. {
  18.    int i, st, iterations = DEFAULT_ITERATIONS;
  19.  
  20.    if( argc == 2 )
  21.        iterations = atoi( argv[1] );
  22.  
  23.    init_mu( &mutex );
  24.  
  25.    /*
  26.     *  --  Test the lock and unlock services
  27.     */
  28.    for(i = 0; i < iterations; i++ )
  29.    {
  30.        st = pthread_mutex_lock( &mutex );
  31.        CHECK(st, "pthread_mutex_lock()");
  32.  
  33.        st = pthread_mutex_unlock( &mutex );
  34.        CHECK(st, "pthread_mutex_unlock()");
  35.    }
  36.  
  37.    /*
  38.     *  --  Lock the mutex, then create a thread that attempts to
  39.     *      lock the mutex.  Release the mutex and allow the child
  40.     *      thread to proceed.
  41.     */
  42.    st = pthread_mutex_lock( &mutex );
  43.    CHECK(st, "pthread_mutex_lock()");
  44.  
  45.    st = pthread_create( &th, NULL, (thread_proc_t) lock, NULL );
  46.    CHECK(st, "pthread_create()");
  47.  
  48.    st = pthread_mutex_unlock( &mutex );
  49.    CHECK(st, "pthread_mutex_unlock()");
  50.  
  51.    sched_yield();
  52.    destroy_mu( &mutex );
  53.    return( EXIT_SUCCESS );
  54. }
  55.  
  56. static void
  57. init_mu( pthread_mutex_t *mu )
  58. {
  59.    int st;
  60.  
  61.    st = pthread_mutex_init( mu, NULL );
  62.    CHECK( st, "pthread_mutex_init()");
  63. }
  64.  
  65. static void
  66. destroy_mu( pthread_mutex_t *mu )
  67. {
  68.    int st;
  69.  
  70.    st = pthread_mutex_destroy( mu );
  71.    CHECK(st, "pthread_mutex_destroy()");
  72. }
  73.  
  74. static void 
  75. lock( void )
  76. {
  77.    int st;
  78.  
  79.    st = pthread_mutex_lock( &mutex );
  80.    CHECK(st, "pthread_mutex_lock()");
  81.  
  82.    st = pthread_mutex_unlock( &mutex );
  83.    CHECK(st, "pthread_mutex_unlock()");
  84.  
  85.    pthread_exit( (void *) SUCCESS );
  86. }
  87.